package cn.tedu.egweibo3.controller;

import cn.tedu.egweibo3.conmon.response.JsonResult;
import cn.tedu.egweibo3.conmon.response.StatusCode;
import cn.tedu.egweibo3.mapper.UserMapper;
import cn.tedu.egweibo3.pojo.dto.UserDTO;
import cn.tedu.egweibo3.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo3.pojo.entity.User;
import cn.tedu.egweibo3.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserDTO userDTO){
        log.error("userDTO:"+userDTO);
        UserVO userVO = userMapper.selectUserByUsername(userDTO.getUsername());
        if(userVO!=null){
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setNickname(userDTO.getNickname());
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.error("userDTO:"+userLoginDTO);
        UserVO userVO = userMapper.selectUserByUsername(userLoginDTO.getUsername());
        log.error("userVO:"+userVO);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if(!userVO.getPassword().equals(userLoginDTO.getPassword())){
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @ApiOperation(value = "获取当前用户")
    @PostMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @ApiOperation("退出登录")
    @PostMapping("logout")
    public JsonResult logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
